package com.levy.effect.ioc.utils;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.levy.effect.ioc.annotation.Inject;

/**
 * 依赖注入辅助类
 * 
 * @author levy
 *
 */
public class AutoInjectHelper {

	/**
	 * bean依赖注入
	 * 
	 * @param beanMap
	 */
	public static void inject(Map<Class<?>, Object> type2beans, Map<String, Object> name2beans) {
		for (Entry<Class<?>, Object> entry : type2beans.entrySet()) {
			Object value = entry.getValue();
			Set<Field> allFields = new HashSet<Field>();
			Field[] fields = value.getClass().getFields();
			for (Field field : fields) {
				allFields.add(field);
			}
			Field[] declaredFields = value.getClass().getDeclaredFields();
			for (Field field : declaredFields) {
				allFields.add(field);
			}
			for (Field field : allFields) {
				field.setAccessible(true);
				Inject injectAnno = field.getAnnotation(Inject.class);
				if (injectAnno != null) {
					String injectV = injectAnno.value();
					// 注解没写bean名 直接注入该字段类型的bean
					if (injectV == null || "".equals(injectV.trim())) {
						Class<?> type = field.getType();
						Object object = type2beans.get(type);
						if (object != null) {
							try {
								field.set(value, object);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					} else {// 自定义bean名

					}
				}
			}
		}
	}
}
